#import "ExifController.h"

#import "ExifItem.h"
#import "Utility.h"

#import "Epeg.h"

@implementation ExifController

//------------------------------------------------------------------------------
- (void) awakeFromNib
{
	[table setDataSource: self];
	[table setDelegate: self];
	[table setAutosaveTableColumns: YES];
	[table setAutosaveName: @"exifdialog.table"];

	[txtFilename setTitleWithMnemonic: @""];
	[txtModified setTitleWithMnemonic: @""];
	[txtFileSize setTitleWithMnemonic: @""];
	[txtImageSize setTitleWithMnemonic: @""];
	[txtExifDate setTitleWithMnemonic: @""];
	[imageView setImage: nil];

	isAscending = YES;
	exifItems = [NSMutableArray arrayWithCapacity: 0];
	[exifItems retain];
}

//------------------------------------------------------------------------------
- (IBAction)closeAction:(id)sender
{
	[mainWindow close];
}

//------------------------------------------------------------------------------
- (NSWindow*) mainWindow
{
	return mainWindow;
}

//------------------------------------------------------------------------------
- (void) setFile:(NSString*) filename
{
	[txtExifDate setTitleWithMnemonic: @""];
	[imageView setImage: nil];

	[exifItems removeAllObjects];
	[txtFilename setTitleWithMnemonic: filename];

	NSFileManager *fileMan = [NSFileManager defaultManager];
	NSDictionary *attrs = [fileMan fileAttributesAtPath
		: filename
		traverseLink: NO];
	NSDate *fileDate = [attrs fileModificationDate];
	[txtModified setTitleWithMnemonic: [fileDate description]];

	unsigned long long size = [attrs fileSize];
	[txtFileSize setTitleWithMnemonic: formatLength((long) size)];


	NSString *thumbState = @"No EXIF data available";

	// Determine the actual image width/height (which may be different than what's stored in
	// the EXIF info; or the EXIF data may not exist).
	Epeg_Image *epeg = epeg_file_open([filename cStringUsingEncoding:NSUTF8StringEncoding]);

	if (nil != epeg)
	{
		int aWidth, aHeight;
		epeg_size_get(epeg, &aWidth, &aHeight);
		epeg_close(epeg);

		[txtImageSize setTitleWithMnemonic: [NSString stringWithFormat:@"%u x %u", aWidth, aHeight]];

		NSDate *exifDate = nil;
		NSImage *thumb = nil;
		getExifData(filename, &exifItems, &exifDate, &thumb);

		if (nil != exifDate)
		{
			[txtExifDate setTitleWithMnemonic: [exifDate description]];

			NSTimeInterval diff = [exifDate timeIntervalSinceDate: fileDate];
			if (diff > 2.0 || diff < -2.0)
			{
				[txtExifDate setTextColor: [NSColor redColor]];
			}
			else
			{
				[txtExifDate setTextColor: [NSColor textColor]];
			}
		}

		if (nil != thumb)
		{
			[imageView setImage: thumb];
			[thumb release];

			NSSize sizeThumbnail = [thumb size];

			// Check to see if the thumbnail has the same aspect ratio as the image
			// NOTE: At least one manufacturer that supports auto-orientation correction (Kodak)
			// has a thumbnail with landscape dimensions when the photo is portrait. The thumbnail
			// has actually been rotated, but it's filled in with black. I can't find other flags
			// (like an orientation flag) to help determine if the thumbnail is correct...
			BOOL thumbWidthBigger = sizeThumbnail.width >= sizeThumbnail.height;
			BOOL imageWidthBigger = aWidth >= aHeight;
			if (thumbWidthBigger != imageWidthBigger)
			{
				thumbState = @"Thumbnail has incorrect aspect ratio";
			}
			else
			{
				thumbState = @"Thumbnail is valid";
			}
		}
		else
		{
			if (nil != exifDate)
			{
				thumbState = @"EXIF contains no thumbnail";
			}
		}
	}
	else
	{
		[txtImageSize setTitleWithMnemonic: @""];
	}

	[txtThumbState setTitleWithMnemonic: thumbState];

	[table reloadData];
}

//------------------------------------------------------------------------------
- (id)tableView:
		(NSTableView *)tableView 
		objectValueForTableColumn:(NSTableColumn *)tableColumn 
		row:(int)rowIndex
{
	if (NO == isAscending)
	{
		rowIndex = [exifItems count] - 1 - rowIndex;
	}

	ExifItem *item = [exifItems objectAtIndex: rowIndex];

	if ([[tableColumn identifier] isEqual: @"type"])
	{
		NSString *value = [NSString stringWithFormat: @"%d", [item type]];
		return value;
	}
	else
	if ([[tableColumn identifier] isEqual: @"tag"])
	{
		NSString *value = [NSString stringWithFormat: @"%d", [item tag]];
		return value;
	}
	else
	if ([[tableColumn identifier] isEqual: @"name"])
	{
		return [item name];
	}
	else
	{
		return [item value];
	}
}

//------------------------------------------------------------------------------
- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
	if (nil == exifItems)
	{
		return 0;
	}

	return [exifItems count];
}

//------------------------------------------------------------------------------
- (void) tableView:(NSTableView*)tv didClickTableColumn:(NSTableColumn *)tableColumn
{
	if (sortedColumn == tableColumn)
	{
		isAscending = !isAscending;
	}
	else
	{
		NSString *colId = [tableColumn identifier];
		if ([colId isEqualToString: @"type"])
		{
			[exifItems sortUsingSelector: @selector(compareExifType:)];
		}
		else
		if ([colId isEqualToString: @"name"])
		{
			[exifItems sortUsingSelector: @selector(compareExifName:)];
		}
		else
		if ([colId isEqualToString: @"value"])
		{
			[exifItems sortUsingSelector: @selector(compareExifValue:)];
		}
		else
		if ([colId isEqualToString: @"tag"])
		{
			[exifItems sortUsingSelector: @selector(compareExifTag:)];
		}
	}

	[self setSortedColumn: tableColumn];
	[table reloadData];
}

//------------------------------------------------------------------------------
- (void) setSortedColumn:(NSTableColumn*) column
{
	// If the column has changed, we need to reset more things.
	if (column != sortedColumn)
	{
		if (nil != sortedColumn)
		{
			[table setIndicatorImage: nil  inTableColumn: sortedColumn];
			[sortedColumn release];
		}

		sortedColumn = column;
		[sortedColumn retain];
		[table setHighlightedTableColumn: sortedColumn];
	}

	// And we always update/set the indicator
	[table setIndicatorImage
		: [NSImage imageNamed: isAscending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
		inTableColumn: sortedColumn];
}

//------------------------------------------------------------------------------
- (void) dealloc
{
	[exifItems release];
	[super dealloc];
}

@end
